package com.isprint.jslx.base64;

import com.alibaba.fastjson.JSONObject;
import com.isprint.jslx.httpclient.HttpClient;
import com.jfinal.kit.StrKit;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by ydw on 2017/7/14.
 */
public class PicTransCode {
    /**
     * 测试了post请求和图片转base64code的main方法
     * @param args
     */
    public static void main(String[] args) {
        String imageStr = getImageStr("E:/0cddc078-a540-44f0-be41-bf4c8617662b.jpg");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("image",imageStr);
        String url="http://lxocr.51sprint.com/api/Default/Ocr";
        String result = HttpClient.httpPost(url, jsonObject, false);
        System.out.println(result);
    }

    /**
     * 把图片code转成文件
     * @param imgCode
     * @param imgPath
     * @return
     */
    public static boolean generateImage(String imgCode,String imgPath){
        if (StrKit.isBlank(imgCode)) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        FileOutputStream outputStream=null;
        try {
            byte[] bytes = decoder.decodeBuffer(imgCode);
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i]<0) {
                    bytes[i]+=256;
                }
            }
            outputStream = new FileOutputStream(imgPath);
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
            return true;
        }catch (Exception e){
            return false;
        }finally {
            if (outputStream != null) {
                outputStream=null;
            }
        }
    }

    /**
     * 把图片加密位base64 code
     * @param imgPath
     * @return
     */
    public static String getImageStr(String imgPath){
        InputStream inputStream=null;
        byte[] data=null;
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            inputStream=new FileInputStream(imgPath);
            data=new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                inputStream=null;
            }
        }
        String imgCode = encoder.encode(data);
        return imgCode;
    }


}
